<?php

namespace ApiWF\Controller;

use Common\Controller\ApibaseController;
use Common\Controller\WsMessageSend;
use Think\Think;

class AuthController extends ApibaseController
{
    /**
     * 获取验证码
     */
    public function getPhoneCode()
    {
        $mobile = I('mobile');
        $checkExist = I('checkExist',true,'boolval');
        return $this->_send_sms_code($mobile, $checkExist);
    }

    /**
     * 注册
     */
    public function register()
    {


        //判断手机验证码
        $code = I('code');
        $mobile = I('post.mobile');
        $this->_verify_sms_code($mobile, $code);

        $user_carno = I('user_carno');
        $id_card_number = I('id_card_number');
        $birthday = substr($id_card_number,6,8);
        $birthday = date_create_from_format('Ymd',$birthday);
        $birthday = $birthday->format('Y-m-d');

        $gender = intval(substr($id_card_number,16,1));
        $sex = $gender%2 ? '男':'女';
        $user_ismarry = I('user_ismarry');

        //验证参数
        $rules = array(
            //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
            array('mobile', 'require', '请补全手机号', 1),
            array('mobile', '', '此手机号已注册会员', 0, 'unique', 3),
            array('password', 'require', '密码不能为空！', 1),
            array('password', '6,16', "密码长度至少6位，最多16位！", 1, 'length', 3),
            //array('nickname', '2,6', "名字长度至少2位，最多6位！", 1, 'length', 3),
        );

        $users_model = M("Users");
        if ($users_model->validate($rules)->create() === false) {
            return $this->error($users_model->getError());
        }

        //验证成功
        $password = I('post.password');
        $user_nicename = I('post.nickname');

        $users_model = M("Users");

        $data = array(
            'user_login' => $user_nicename,
            'user_email' => '',
            'mobile' => $mobile,
            'user_nicename' => '',
            'user_pass' => sp_password($password),
            'last_login_ip' => get_client_ip(0, true),
            'last_login_time' => date("Y-m-d H:i:s"),
            'user_status' => 1,
            "user_type" => 2,//会员
            'sex' => $sex,
            'birthday'=>$birthday,
        );

        $result = $users_model->add($data);
        if ($result) {
            //更新用户附加表

            $attrM = D('UsersAttr');
            if (!$attrM->create()) {
                //用户附加表验证
                // 如果创建失败 表示验证没有通过 输出错误提示信息
                $this->error($attrM->getError());
            } else {
                // 验证通过 可以进行其他数据操作


                $data_attr = [
                    'uid' => $result,
                    'user_carno' => $user_carno,
                    'id_card_number' => $id_card_number,
                    'user_ismarry' => $user_ismarry,
                ];
                $attrM->where(['uid'=>$result])->delete();
                $attrM->add($data_attr);
            }
            //生成token
            $tokenArray = $this->createTokenStringByUserId($result);
            //删除验证码缓存
            S($mobile, null);

            //注册奖励
            $reward_coin = 999999;
            //1:金币抽奖 2:金币奖品 3:积分兑换 4:新手任务 5:每日签到 6:金币兑换 7:参加活动 8:退吹活动 9:新手任务 10:注册
            //$this->addCoinRecord($result,10, '注册奖励', "新用户奖励:{$reward_coin}", $reward_coin);
            //$tokenArray['para_debug'] = I('param.');
            $this->jsonReturn($tokenArray, '注册成功');

        } else {
            $this->error("注册失败！");
        }

    }

    /**
     * 登陆
     */
    public function login()
    {
        //参数验证
        $users_model = M("Users");
        $rules = array(
            //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
            array('mobile', '/(^(13\d|15[^4\D]|17[13678]|18\d)\d{8}|170[^346\D]\d{7})$/', '无效手机号码！', 1),
            array('user_pass', 'require', '密码不能为空！', 1),
        );

        if ($users_model->validate($rules)->create() === false) {
            $this->error($users_model->getError());
        }


        $where['user_status'] = 1;
        $where['mobile'] = I('post.mobile');
        $where['user_type'] = 2;

        $result = $users_model->where($where)->field('id,user_pass')->find();

        if (!empty($result)) {
            //验证密码
            $password = I('user_pass');
            if (sp_compare_password($password, $result['user_pass'])) {
                //写入此次登录信息
                $data = array(
                    'last_login_time' => date("Y-m-d H:i:s"),
                    'last_login_ip' => get_client_ip(0, true),
                );
                $users_model->where(array('id' => $result["id"]))->save($data);
                //生成token  隐藏密码 显示基本信息
                $uid = $result['id'];
                $tokenArray = $this->createTokenStringByUserId($uid);

                $this->jsonReturn($tokenArray, '登录成功!!!');
            } else {
                $this->error("密码错误！");
            }
        } else {
            $this->error("用户名不存在或已被拉黑！");
        }

    }


    /**
     * 忘记密码 发送验证码
     */

    public function resetPassword()
    {
        $code = I('code');
        $mobile = I('mobile');
        $this->_verify_sms_code($mobile, $code);

        //验证通过之后 重新密码;

        //验证密码合法性
        $users_model = M("Users");
        $rules = array(
            //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
            array('password', 'require', '密码不能为空！', 1),
            array('password', '5,20', "密码长度至少5位，最多20位！", 1, 'length', 3),
        );
        if ($users_model->validate($rules)->create() === false) {
            $this->error($users_model->getError());
        }

        //修改密码
        $user_pass = sp_password(I('password'));
        $rest = $users_model->where(compact('mobile'))->save(compact('user_pass'));

        if ($rest) {
            //删除验证码缓存
            S($mobile, null);
            $this->success('密码修改成功请重新登录');
        } else {
            $this->error('修改密码失败');
        }


    }


    /**
     * 修改密码
     */
    public function changePassword()
    {
        $uid = $this->parseTokenUID();

        $db_old_pass = sp_password(I('old_pass'));
        $db_new_pass = sp_password(I('new_pass'));

        $where['uid'] = $uid;
        $where['user_pass'] = $db_old_pass;

        $res = D('Users')->where($where)->save(['user_pass' => $db_new_pass]);

        if ($res) {
            //重新生产token
            $tokenArray = $this->createTokenStringByUserId($uid);
            $tokenArray['uid'] = $uid;
            $this->jsonReturn($tokenArray, '密码修改成功');
        } else {
            $this->error('密码错误');
        }
    }


    /**
     * 发送手机验证码
     */
    protected function _send_sms_code($mobile,$checkExist)
    {

        //验证手机号码合法性
        $pattern = '#^(13\d|14[57]|15[012356789]|18\d|17[013678])\d{8}$#';
        $res = preg_match($pattern, $mobile);
        if (!$res) {
            $this->error('请补全手机号!');
        }

        $anyUser = D('Users')->where(compact('mobile'))->find();

        if ($checkExist) {
            //重置密码
            if (empty($anyUser)) {
                $this->error('账号不存在');
            }
        }else{
            //注册
            if (!empty($anyUser)) {
                $this->error('手机号码已经被注册');
            }

        }

        $code = S($mobile);
        if (empty($code)) {
            $code = rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9);


            //发送手机验证码
            $username = C('SMS_ACCOUNT');                            //改为实际账户名
            $password = C('SMS_PASSWORD');                            //改为实际短信发送密码
            $mobiles = $mobile;                    //目标手机号码，多个用半角“,”分隔
            $content = "【世界之花】您的验证码为：$code 切勿泄露给他人，若非本人操作，请忽略！";
            $extnumber = "";
            $plansendtime = '';                        //定时短信发送时间,格式 2016-06-06T06:06:06，null或空串表示为非定时短信(即时发送)
            //$plansendtime='2016-06-06T06:06:06'
            $result = WsMessageSend::send($username, $password, $mobiles, $content, $extnumber, $plansendtime);
            if ($result == null) {
                return $this->error('接口调用失败');
            } else {
                S($mobile, $code, 250);
                //print_r($result);
                $msgDebug = "返回信息提示：" . $result->Description . "\n";
                $msgDebug .= "返回状态为：" . $result->StatusCode . "\n";
                $msgDebug .= "返回余额：" . $result->Amount . "\n";
                $msgDebug .= "返回成功短信数：" . $result->SuccessCounts . "\n";
            }
        }
        $msg = '验证码已经发送,有效期为四分钟';
        $this->jsonReturn(compact('code', 'msgDebug'), $msg);
    }

    /**
     * 验证手机验证码
     * @param $moblie 手机号码
     * @param $code 收到的验证码
     */
    protected function _verify_sms_code($moblie, $code)
    {
        $db_code = S($moblie);
        if (empty($db_code)) {
            return $this->error('超过三分钟,验证码失效');
        } else {
            if ($db_code !== $code) {
                return $this->error('输入验证码有误!');
            }
        }
    }
}

